package vip.mate.core.mybatis.handler;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * 自动填充模型数据
 *
 * @author pangu
 * @since 2023/1/2
 */
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
    private final static String CREATE_TIME = "createTime";
    private final static String CREATED_BY = "createdBy";
    private final static String UPDATE_TIME = "updateTime";
    private final static String UPDATED_BY = "updatedBy";
    private final static String ORG_ID = "orgId";
    private final static String VERSION = "version";
    private final static String DELETED = "deleted";

    @Override
    public void insertFill(MetaObject metaObject) {
        Long createdBy = NumberUtil.parseLong(getFieldValByName(CREATED_BY, metaObject).toString());
        Long updatedBy = NumberUtil.parseLong(getFieldValByName(UPDATED_BY, metaObject).toString());
        Long orgId = NumberUtil.parseLong(getFieldValByName(ORG_ID, metaObject).toString());
        Date date = new Date();

        // 创建者
        strictInsertFill(metaObject, CREATED_BY, Long.class, createdBy);
        // 创建时间
        strictInsertFill(metaObject, CREATE_TIME, Date.class, date);
        // 更新者
        strictInsertFill(metaObject, UPDATED_BY, Long.class, updatedBy);
        // 更新时间
        strictInsertFill(metaObject, UPDATE_TIME, Date.class, date);
        // 创建者所属机构
        strictInsertFill(metaObject, ORG_ID, Long.class, orgId);
        // 版本号
        strictInsertFill(metaObject, VERSION, Integer.class, 0);
        // 删除标识
        strictInsertFill(metaObject, DELETED, Integer.class, 0);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long updatedBy = NumberUtil.parseLong(getFieldValByName(UPDATED_BY, metaObject).toString());
        // 更新者
        strictUpdateFill(metaObject, UPDATED_BY, Long.class, updatedBy);
        // 更新时间
        strictUpdateFill(metaObject, UPDATE_TIME, Date.class, new Date());
    }
}
